/**
 * LigHistory存储模块
 */
import { BaseStorage, DBManager, StorageConfig } from './dbBase';

// LigHistory记录类型定义
export interface LigHistoryRecord {
    id: number;
    name: string;
}

// LigHistory存储配置
export const LIG_HISTORY_STORAGE_CONFIG: StorageConfig = {
    storageName: 'LigHistory'
};

/**
 * 初始化LigHistory存储
 */
export const initLigHistoryStorage = (db: IDBDatabase): void => {
    if (!db.objectStoreNames.contains(LIG_HISTORY_STORAGE_CONFIG.storageName)) {
        const store = db.createObjectStore(LIG_HISTORY_STORAGE_CONFIG.storageName, { keyPath: 'id' });
        store.createIndex('id', 'id', { unique: true });
        console.log(`创建存储对象: ${LIG_HISTORY_STORAGE_CONFIG.storageName}`);
    }
};

/**
 * LigHistory存储类
 * 提供LigHistory记录的CRUD操作
 */
export class LigHistoryStorage extends BaseStorage<LigHistoryRecord> {
    protected storageConfig: StorageConfig = LIG_HISTORY_STORAGE_CONFIG;

    constructor(dbManager: DBManager) {
        super(dbManager);
    }

    /**
     * 添加LigHistory记录
     */
    async add(record: LigHistoryRecord): Promise<boolean> {
        try {
            const storeName = this.storageConfig.storageName;
            await (this.dbManager as any).executeTransaction(
                storeName,
                'readwrite',
                (store: IDBObjectStore) => {
                    const request = store.add(record);
                    request.onsuccess = () => {
                        console.log('LigHistory记录添加成功:', record.id);
                    };
                    return request;
                }
            );
            return true;
        } catch (error) {
            console.error('LigHistory记录添加失败:', error);
            return false;
        }
    }

    /**
     * 批量添加LigHistory记录
     */
    async addBatch(records: LigHistoryRecord[]): Promise<boolean> {
        if (records.length === 0) {
            return true;
        }

        try {
            let successCount = 0;
            let errorCount = 0;

            for (const record of records) {
                try {
                    await this.add(record);
                    successCount++;
                } catch (error) {
                    errorCount++;
                    console.error('批量添加记录失败:', record.id, error);
                }
            }

            if (errorCount === 0) {
                console.log(`批量添加${successCount}条LigHistory记录成功`);
                return true;
            } else {
                console.warn(`批量添加LigHistory记录部分成功: 成功${successCount}条，失败${errorCount}条`);
                return successCount > 0;
            }
        } catch (error) {
            console.error('批量添加LigHistory记录失败:', error);
            return false;
        }
    }

    /**
     * 更新LigHistory记录
     */
    async update(record: LigHistoryRecord): Promise<boolean> {
        try {
            const storeName = this.storageConfig.storageName;
            await (this.dbManager as any).executeTransaction(
                storeName,
                'readwrite',
                (store: IDBObjectStore) => {
                    const request = store.put(record);
                    request.onsuccess = () => {
                        console.log('LigHistory记录更新成功:', record.id);
                    };
                    return request;
                }
            );
            return true;
        } catch (error) {
            console.error('LigHistory记录更新失败:', error);
            return false;
        }
    }

    /**
     * 删除LigHistory记录
     */
    async delete(id: number): Promise<boolean> {
        try {
            const storeName = this.storageConfig.storageName;
            await (this.dbManager as any).executeTransaction(
                storeName,
                'readwrite',
                (store: IDBObjectStore) => {
                    const request = store.delete(id);
                    request.onsuccess = () => {
                        console.log('LigHistory记录删除成功:', id);
                    };
                    return request;
                }
            );
            return true;
        } catch (error) {
            console.error('LigHistory记录删除失败:', error);
            return false;
        }
    }

    /**
     * 获取单条LigHistory记录
     */
    async get(id: number): Promise<LigHistoryRecord | null> {
        try {
            const storeName = this.storageConfig.storageName;
            const result = await (this.dbManager as any).executeTransaction(
                storeName,
                'readonly',
                (store: IDBObjectStore) => store.get(id)
            );
            return result || null;
        } catch (error) {
            console.error('获取LigHistory记录失败:', error);
            return null;
        }
    }

    /**
     * 获取所有LigHistory记录
     */
    async getAll(): Promise<LigHistoryRecord[]> {
        try {
            const storeName = this.storageConfig.storageName;
            const result = await (this.dbManager as any).executeTransaction(
                storeName,
                'readonly',
                (store: IDBObjectStore) => store.getAll()
            );
            return result || [];
        } catch (error) {
            console.error('获取所有LigHistory记录失败:', error);
            return [];
        }
    }

    /**
     * 清空所有LigHistory记录
     */
    async clearAll(): Promise<boolean> {
        try {
            const storeName = this.storageConfig.storageName;
            await (this.dbManager as any).executeTransaction(
                storeName,
                'readwrite',
                (store: IDBObjectStore) => {
                    const request = store.clear();
                    request.onsuccess = () => {
                        console.log('清空所有LigHistory记录成功');
                    };
                    return request;
                }
            );
            return true;
        } catch (error) {
            console.error('清空所有LigHistory记录失败:', error);
            return false;
        }
    }
} 